package org.itboys.mobile.controller.web;

import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.entity.mysql.order.SundayOrder;
import org.itboys.mobile.entity.mysql.order.SundayOrderProduct;
import org.itboys.mobile.service.mysql.front.SundayFrontOrderService;
import org.itboys.mobile.service.mysql.web.order.SundayOrderService;
import org.itboys.mobile.util.ResponseMessage;
import org.itboys.param.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作者：jiangxiong
 * 日期：2016年11月25日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_订单_后台_controller
 */
@Controller
@RequestMapping("/sunday/web/order")
public class SundayOrderController extends BaseController {
    @Autowired
    private SundayOrderService orderService;
    @Autowired
    private SundayFrontOrderService fontOrderService;

    /**
     * 订单模块主页
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String index(
            HttpServletRequest request,
            Model model
            ){

        return "/sunday/order/index";
    }

    /**
     * 订单详情
     * @param request
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/findOne")
    public String findOne(HttpServletRequest request,@RequestParam(value="id",required=true) Long id,Model model){
        SundayOrder order = orderService.findOne(id);
        model.addAttribute("order",order);
        return"/sunday/order/input";
    }

    /**
     *
     * @param request
     * @param response
     * @param orderStatus
     * @param discountWay 1使用优惠券2使用爱购币3使用余额4使用贝壳
     */
    @RequestMapping("/select")
    public void select(HttpServletRequest request,HttpServletResponse response,
                       @RequestParam(value="orderStatus",required=true) Integer orderStatus,
                       @RequestParam(value="discountWay",required=false) Integer discountWay){
        try {
            PageResult<SundayOrder> result = orderService.selectOrder(request,orderStatus,discountWay);
            JsonPageUtils.renderJsonPage(result.getTotal(),result.getData(),response);
        } catch (Exception e) {

            String msg ="";
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
            }else{
                msg= CommonConstants.ERROMSG;
                logger.error("/sunday/web/order/select------"+e.getMessage());
            }
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE,msg));
        }
    }

    @RequestMapping("/product/select")
    public void product_select(HttpServletRequest request,
                       HttpServletResponse response,
                       @RequestParam(value="orderId",required=true) Long orderId
    ) {
        try {

            PageResult<SundayOrderProduct> result = orderService.selectOrderProduct(request,orderId);
            JsonPageUtils.renderJsonPage(result.getTotal(),result.getData(),response);
        } catch (Exception e) {

            String msg ="";
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
            }else{
                msg= CommonConstants.ERROMSG;
                logger.error("/sunday/web/order/product/select------"+e.getMessage());
            }
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE,msg));
        }

    }

    /**
     * 订单发货
     * @param request
     * @param response
     * @param orderId

     */
    @RequestMapping("/send")
    public void send(HttpServletRequest request,
                     HttpServletResponse response,
                            @RequestParam(value="orderId",required=true) Long orderId,
                            @RequestParam(value="sendCompany",required=false)String sendCompany,
                            @RequestParam(value="sendCompanyCode",required=false)String sendCompanyCode,
                            @RequestParam(value="sendCode",required=false) String sendCode
    ) {
        try {
            orderService.sendOrder(orderId,  sendCompany,sendCompanyCode,  sendCode);
            ResponseMessage.success();
        } catch (Exception e) {
            String msg ="";
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
            }else{
                msg= CommonConstants.ERROMSG;
                logger.error("/sunday/web/order/send------"+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(CommonConstants.FAIL_CODE, msg);
        }
    }

    /**
     * 订单退款,退货
     * @param request
     * @param response
     * @param type 类型:1-退款,2-退货
     */
    @RequestMapping("/back")
    public void back(HttpServletRequest request,HttpServletResponse response,
                     @RequestParam(value="orderId",required=true) Long orderId,
                     @RequestParam(value="type",required=true) Integer type){
        try {
            orderService.back(orderId,type);
            ResponseMessage.success();
        } catch (Exception e) {

            String msg ="";
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
            }else{
                msg= CommonConstants.ERROMSG;
                logger.error("/sunday/web/order/back------"+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(CommonConstants.FAIL_CODE, msg);
        }
    }

    /**
     * 取消订单
     * @param request
     * @param response
     * @param orderId
     */
    @RequestMapping(value="/cancel",method= { RequestMethod.POST,RequestMethod.GET})
    public void cancel(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单ID【参与签名】") @RequestParam(value = "orderId", required = true) Long orderId
    ) {
        try{

            orderService.cancelOrder(orderId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/web/order/cancel----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 确认收货
     * @param request
     * @param response
     * @param orderId
     * @param memberId
     */
    @RequestMapping(value="/confirmReceive",method= { RequestMethod.POST,RequestMethod.GET})
    public void confirmReceive(HttpServletRequest request,
                               HttpServletResponse response,
                               @ApiParam(required = true, name = "orderId", value = "订单ID【参与签名】") @RequestParam(value = "orderId", required = true) Long orderId,
                               @ApiParam(required = true, name = "memberId", value = "用户ID【参与签名】") @RequestParam(value = "memberId", required = true) Long memberId

    ) {
        try{
            if(LongUtil.isNotZreo(AdminSessionHolder.getAdminUserId())){
                fontOrderService.confirmReceive(orderId,memberId);
            }

            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/web/order/confirmReceive----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/excel",method= { RequestMethod.POST,RequestMethod.GET})
    public void excel(HttpServletRequest request,
                               HttpServletResponse response,
                                @RequestParam(value = "orderId", required = true) Long orderId,
                                 @RequestParam(value = "orderNo", required = true) String orderNo
    ) {
        try{
            orderService.excel(orderId,orderNo);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/web/order/excel----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
}
